// 全局变量
let currentPlayingSong = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 绑定下载按钮事件
    bindDownloadButtons();
    
    // 绑定歌曲点击事件
    bindSongClickEvents();
    
    // 绑定模态框关闭事件
    bindModalEvents();
});

// 绑定下载按钮事件
function bindDownloadButtons() {
    const downloadButtons = document.querySelectorAll('.btn-download');
    downloadButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.stopPropagation(); // 阻止事件冒泡
            const songId = this.getAttribute('data-song-id');
            showDownloadLinks(songId);
        });
    });
}

// 绑定歌曲点击事件
function bindSongClickEvents() {
    const songItems = document.querySelectorAll('.song-item');
    songItems.forEach(item => {
        item.addEventListener('click', function(e) {
            // 如果点击的是下载按钮，则不播放
            if (e.target.classList.contains('btn-download')) {
                return;
            }
            
            const songId = this.getAttribute('data-song-id');
            const songSrc = this.getAttribute('data-song-src');
            playSong(songSrc);
            
            // 高亮当前播放的歌曲
            document.querySelectorAll('.song-item').forEach(item => {
                item.style.backgroundColor = 'white';
            });
            this.style.backgroundColor = '#e3f2fd';
            currentPlayingSong = songId;
        });
    });
}

// 显示下载链接
function showDownloadLinks(songId) {
    const modal = document.getElementById('downloadModal');
    const downloadLinksContainer = document.getElementById('downloadLinks');
    
    // 显示加载动画
    downloadLinksContainer.innerHTML = '<div class="loading"></div> 正在获取下载链接...';
    modal.style.display = 'block';
    
    // 调用API获取下载链接
    fetch(`/api/song/${songId}/download_urls`)
        .then(response => response.json())
        .then(data => {
            if (data.length > 0) {
                displayDownloadLinks(data);
            } else {
                downloadLinksContainer.innerHTML = '<p>暂无可用下载链接</p>';
            }
        })
        .catch(error => {
            console.error('获取下载链接失败:', error);
            downloadLinksContainer.innerHTML = '<p>获取下载链接失败，请稍后重试</p>';
        });
}

// 显示下载链接列表
function displayDownloadLinks(links) {
    const downloadLinksContainer = document.getElementById('downloadLinks');
    
    if (links.length === 0) {
        downloadLinksContainer.innerHTML = '<p>暂无可用下载链接</p>';
        return;
    }
    
    let linksHtml = '';
    links.forEach(link => {
        linksHtml += `<a href="${link.value}" target="_blank" class="download-link">${link.type}</a>`;
    });
    
    downloadLinksContainer.innerHTML = linksHtml;
}

// 播放歌曲
function playSong(songSrc) {
    const player = document.getElementById('player');
    if (player) {
        player.src = songSrc;
        player.play()
            .then(() => {
                console.log('开始播放歌曲');
            })
            .catch(error => {
                console.error('播放失败:', error);
                alert('播放失败，请检查音频链接是否有效');
            });
    }
}

// 绑定模态框事件
function bindModalEvents() {
    const modal = document.getElementById('downloadModal');
    const closeBtn = document.querySelector('.close');
    
    // 点击关闭按钮关闭模态框
    if (closeBtn) {
        closeBtn.addEventListener('click', function() {
            modal.style.display = 'none';
        });
    }
    
    // 点击模态框外部关闭模态框
    window.addEventListener('click', function(event) {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    });
    
    // 按ESC键关闭模态框
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            modal.style.display = 'none';
        }
    });
}

// 重新加载随机歌曲
function reloadRandomSongs() {
    location.reload();
}